<?php
/**
 * 接口控制器
 */
namespace Admin\Controller;
use Think\Controller;
use Think\Log;
use Org\Util\Page;

class OfferController extends BaseController
{
	public function index(){
    $this->display();
  }


  public function offerList()
  {

    $_listrows = I('request.verypageshowcount', '', 'trim');

        //$_where['transaction_type'] = 1;

    $check = I('request.check',-1,'intval');
    if( $check != -1){
      $_where['`check`']=$check;
    }

    $keywords = I('request.keywords','','trim');
    if(!empty($keywords)){
      $_where['purchaseame|linkname|goodsname']=array('like',"%{$keywords}%");
    }

    $start_time = I('request.start_time','','trim');
    $end_time = I('request.end_time','','trim');
    $str='';
        //如果两个为空，没有条件
        //否则 一个为空，一个有值，两个有值 
    if(!(empty($start_time) && empty($end_time))){ 
      $start_time = empty($start_time)?date("Y-m-d H:i:s"):$start_time;
      $end_time = empty($end_time)?date("Y-m-d H:i:s"):$end_time;

      if($start_time>$end_time){
       $temp=$end_time;
       $end_time=$start_time;
       $start_time=$temp;
     }  

     $str =" and a.createtime between '".$start_time." 00:00:01' and '".$end_time." 23:59:59'";

   }  
   $str.="and a.ishandle = 1";
   $str = ltrim(trim($str),'and');
   if(!empty($str)){
    $_where['_string']=$str;
  }
  $where_order['where'] = $_where;
  /*$where_order['order'] = ' last_transaction_time desc ';*/
  $where_order['listrows'] = $_listrows;
  $where_order["id"]="load_tb_div";
  $where_order["field"]="a.*,b.offer_number,b.actual_number,b.offer_price,b.sendtime,b.isbatch,b.iscomfirm,c.purchaseame,d.linkname,e.goodsname,e.goodsid,u.user_name";
  $where_order['alias']="a";
  $where_order['order']="createtime desc";
  $where_order["join"] =array('left join '.$this->dbprefix.'wx_offerlist b on a.offerid=b.offerid',' left join '.$this->dbprefix.'wx_purchase c on a.purchaseid=c.purchaseid',' left join '.$this->dbprefix.'wx_supplier d on a.sp_id=d.sp_id',' left join '.$this->dbprefix.'wx_purchaselist e on b.listid=e.listid',' inner join '.$this->dbprefix.'admin_user u on a.operationuser=u.user_id');
  $_datalist = $this->_getListsFromModel('wx_offer', $where_order);
  $Arr = array('默认','交易成功','验证发票','等收发票','交易失败','等待收货','验证失败');
  $Arr2 =array('提交','有效','部分有效');
  $this->assign('arr',$Arr);
  $this->assign('arr2',$Arr2);
  $this->assign('_datalist', $_datalist);
  $this->display(); 


}

public function add_purchase(){
 $this->display();
}

public function addPurchase(){
  $data['purchaseid'] = guid() ;
  $data['purchaseame'] =I('post.username');
  $data['lasttime'] =I('post.end_time');
  $data['remark'] =I('post.remark');
  $data['isactive'] =I('post.in_or_out');
  $data['operationuser'] = $_SESSION['admin_id'];
  $data['createtime'] = date('Y-m-d H:i:s');
  $exe_scriptstr = "<script>
  setTimeout(function(){
    var win=    art.dialog.opener;
    win._reload_currentpage_datalist('load_tb_div');
    art.dialog.close();
  },500);
</script>";

$res = D('wx_purchase')->add($data);

if($res != false){
            //添加成功后，输出文本，把js脚本一起输出，前台只要html到某个div里就能够执行js
  $this->success('操作成功！' . $exe_scriptstr);
}else{


 $this->success('操作失败！' . $exe_scriptstr);
}
$this->display();


}

public function update_wx_purchase(){
  $map['purchaseid'] = I('get.purchaseid');
  $list = D('wx_purchase')->where($map)->find();

  if($list != false){
    $this->assign('list',$list);
    $this->display();
  }
}

public function save_wx_purchase(){
  $map['purchaseid'] = I('post.id');
  $data['purchaseame'] =I('post.username');
  $data['isactive'] =I('post.in_or_out');
  $data['lasttime'] =I('post.end_time');
  $data['remark'] =I('post.remark');
  $data['operationuser'] = $_SESSION['admin_id'];
  $data['createtime'] = date('Y-m-d H:i:s');
  $exe_scriptstr = "<script>
  setTimeout(function(){
    var win=    art.dialog.opener;
    win._reload_currentpage_datalist('load_tb_div');
    art.dialog.close();
  },1000);

</script>";


$res = D('wx_purchase')->where($map)->save($data);

if($res != false){

                //添加成功后，输出文本，把js脚本一起输出，前台只要html到某个div里就能够执行js
  $this->success('操作成功！' . $exe_scriptstr);
}else{

                //添加成功后，输出文本，把js脚本一起输出，前台只要html到某个div里就能够执行js
  $this->error('操作失败！' . $exe_scriptstr); 
}
$this->display();


}

public function delete_wx_purchase(){
 if(IS_GET){
  $map['purchaseid'] = I('get.id');
  $row = D('wx_purchase')->where($map)->delete();
  if($row != false){
    $this->success("删除成功") ;
  }else{
    $this->error("删除失败") ;
  }

}

}


//验证发票
public function validate(){
 if(empty($_GET['offerid'])){
  $this->error('验证异常');
}

$where['offerid'] = $_GET['offerid'];
$offer = D('wx_offer')->where($where)->find();
if($offer == fasle){
 $this->error('获取信息失败');
}

$map['a.offerid'] =$_GET['offerid'];
$list = D('wx_offer')->alias('a')
->field("a.*,b.offer_number,b.actual_number,b.offer_price,b.sendtime,b.isbatch,b.iscomfirm,c.purchaseame,d.linkname,e.goodsname,e.goodsid,u.user_name")
->join('left join '.$this->dbprefix.'wx_offerlist b on a.offerid=b.offerid')
->join(' left join '.$this->dbprefix.'wx_purchase c on a.purchaseid=c.purchaseid')
->join(' left join '.$this->dbprefix.'wx_supplier d on a.sp_id=d.sp_id')
->join(' inner join '.$this->dbprefix.'admin_user u on a.operationuser=u.user_id')
->join(' left join '.$this->dbprefix.'wx_purchaselist e on b.listid=e.listid')
->where($map)
->select();
if($list == false){
 $this->error('获取信息失败');
}
//获取到该采购单的发票
$invoiceurl_list = D('wx_offer')->field('invoiceurl')->where($where)->find();
$invoiceurl_arr = explode(',', $invoiceurl_list['invoiceurl']);
/*    print_r($invoiceurl_arr);exit;*/
$Arr = array('默认','交易成功','验证发票','等收发票','交易失败','等待收货','验证失败');
$Arr2 =array('提交','有效','部分有效');
$this->assign('arr',$Arr);
$this->assign('arr2',$Arr2);
$this->assign('offer',$offer);
$this->assign('invoiceurl_arr',$invoiceurl_arr);
$this->assign('offerid',$where['offerid']);
$this->assign('list',$list);
$this->display();
}

public function invoice(){
  if($_GET['offerid'] == "" || $_GET['state'] ==""){
    $ret=array("staute"=>"error","msg"=>"保存数据失败");
    $this->ajaxReturn($ret);
    exit;
  }
  $state = $_GET['state'];
  $offerid= $_GET['offerid'];
//获取供应商信息
  $data = array();
  $mobile =D('wx_offer')->field('b.moblie')->alias('a')->join(" left join ".$this->dbprefix."wx_supplier b on a.sp_id= b.sp_id")->where('a.offerid ="'.$offerid.'"')->find();
  $data['mobile'] = $mobile['moblie'];
    //验证不通过 将状态改为check = 6
  if($state == 0){
   $db = M();
   $time =  date('Y-m-d H:i:s',strtotime(" +16 h"));
   $res = $db->execute("update ".$this->dbprefix."wx_offer set `check` = 6,invoiceurl='',createtime='".$time."' where offerid='".$offerid."'");
   if($res){
/*              获取openid
              $spid  =D('wx_offer')->field('sp_id')->where("offerid = '".$offerid."'")->find();
              if(!$spid){
                $this->error('获取供应商是失败');
              } 
               $openidList = D('wx_supplier')->field('openid')->where("sp_id='".$spid['sp_id']."'")->find();
               if(!$openidList){
                  $this->error('获取openid是失败');
                } 
                  $data['touser'] =$openidList['openid']; 'ok2Dgvorz_g_GMqrfRBSN8U5eKVE';
                  $data['msgtype'] = "text";

                  $data['text']['content'] = urlencode("<a href='".$url."'>您上传的发票不合格，请重新上传！</a>");
              //微信接口发消息
              $wxObj = $this->init();
              $result=$wxObj->sendCustomMessage($data);
              if( $result['errcode'] != 0 || $result['errmsg'] != "ok"){
 
                  $this->error('信息发送失败!');
      
                  exit;*/

               // 验证完成发送短信供应商
                      // $data['mobile'] = "0480005462";
                  $url = C("WEBURL").'/wx.php/Offer/user_offer?offerid='.$offerid;
                  $data['content'] = "我们的管理员已经审核了您的发票，请点击该连接查看(".$url.")，您发票不合格，请重新上传！";

                       //请求mobile/smsmessage_au.php
                  $url=C("WEBURL")."/mobile/smsmessage_au.php?act=purchase_message";
                       //添加个参数区分需不需要构建session
                      file_put_contents('log.txt', '\r\n'.date('Y-m-d H:i:s').$data['mobile'].$data['content'],FILE_APPEND);// 这个函数支持版本(PHP 5) 

                      $result= $this->http_request($url,$data);
                      if($result=="" ||empty($result)){

                        $ret=array("staute"=>"error","msg"=>"短信发送失败！");
                        $this->ajaxReturn($ret);
                        exit;

                      }
                      
                      $ret=array("staute"=>"error","msg"=>"操作成功");
                      $this->ajaxReturn($ret);
                      exit;
                    }else{
                     $ret=array("staute"=>"error","msg"=>"操作失败");
                     $this->ajaxReturn($ret);
                     exit;
                   }

                 } 
    //验证通过  将状态改为check = 5 
                 if($state ==1){
                  $db = M();
                  $time =  date('Y-m-d H:i:s',strtotime(" +16 h"));
                  $res = $db->execute("update ".$this->dbprefix."wx_offer set `check` = 5,createtime='".$time."' where offerid='".$offerid."'");
                  if($res){
           //将采购单的数量减去
                   $offer_list = D('wx_offerlist')->field('listid,actual_number')->where('offerid = "'.$offerid.'"')->select();
                   foreach ($offer_list as $key => $value) {
                     $purchase_list = D('wx_purchaselist')->field('number,listid')->where('listid = "'.$value['listid'].'"')->find();
                     $new_number = $purchase_list['number']-$value['actual_number'];
                     $result = $db->execute("update ".$this->dbprefix."wx_purchaselist set number='".$new_number."' where listid='".$value['listid']."'");
                   }


                   $data['content'] = "我们的管理员已经审核了您的发票，验证通过！请去用户中心查看，尽快备货，送货！";

                       //请求mobile/smsmessage_au.php
                   $url=C("WEBURL")."/mobile/smsmessage_au.php?act=purchase_message";
                       //添加个参数区分需不需要构建session
                      file_put_contents('log.txt', '\r\n'.date('Y-m-d H:i:s').$data['mobile'].$data['content'],FILE_APPEND);// 这个函数支持版本(PHP 5) 

                      $result= $this->http_request($url,$data);
                      if($result=="" ||empty($result)){
                       $ret=array("staute"=>"error","msg"=>"短信发送失败！");
                       $this->ajaxReturn($ret);
                       exit;

                     }
                     $ret=array("staute"=>"error","msg"=>"操作成功");
                     $this->ajaxReturn($ret);
                     exit;                   
                   }else{
                    $ret=array("staute"=>"error","msg"=>"操作失败");
                    $this->ajaxReturn($ret);
                    exit;
                  }
                }


      //交易成功
                if($state == 3){
                  $db = M();
                  $time = $time =  date('Y-m-d H:i:s',strtotime(" +16 h"));
                  $res = $db->execute("update ".$this->dbprefix."wx_offer set `check` = 1,createtime='".$time."' where offerid='".$offerid."'");
                  if($res){

                    $data['content'] = "本次采购交易完成，合作愉快，谢谢！";
                       //请求mobile/smsmessage_au.php
                    $url=C("WEBURL")."/mobile/smsmessage_au.php?act=purchase_message";
                       //添加个参数区分需不需要构建session
                      file_put_contents('log.txt', '\r\n'.date('Y-m-d H:i:s').$data['mobile'].$data['content'],FILE_APPEND);// 这个函数支持版本(PHP 5) 

                      $result= $this->http_request($url,$data);
                      if($result=="" ||empty($result)){
                        $ret=array("staute"=>"error","msg"=>"短信发送失败！");
                        $this->ajaxReturn($ret);
                        exit;

                      }
                      $ret=array("staute"=>"error","msg"=>"操作成功");
                      $this->ajaxReturn($ret);
                      exit;                         
                    }else{
                      $ret=array("staute"=>"error","msg"=>"操作失败");
                      $this->ajaxReturn($ret);
                      exit;                           
                    }
                  }
                }   



        //HTTP请求（支持HTTP/HTTPS，支持GET/POST）
                function http_request($url, $data = null){
                  $curl = curl_init();
                  curl_setopt($curl, CURLOPT_URL, $url);
                  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
                  curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
                  if (!empty($data)){
                    curl_setopt($curl, CURLOPT_POST, 1);
                    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                  }
                  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                  $output = curl_exec($curl);
                  curl_close($curl);
                  return $output;
                }
              }



              ?>

